/**
 * @Date: 2022-03-09 20:30:53
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-03-14 09:35:39
 * @FilePath: \zhihuReal\middlewares\cheack.js
 * @Description: 检查相关中间件
 */
const User = require('../model/usersMdl')
const Topic = require('../model/topicMdl')
const Question = require('../model/questionMdl')
const Comment = require('../model/commentsMdl')
const Answer = require('../model/answersMdl')
const cheackUserExist = async (ctx, next) => {
    const user = await User.findById(ctx.params.id)
    if (!user) {
        ctx.throw(404, '用户不存在')
    }
    await next()
}
const cheackTopicExist = async (ctx, next) => {
    const topic = await Topic.findById(ctx.params.id)
    if (!topic) {
        ctx.throw(404, '话题不存在')
    }
    await next()
}
const cheackQuestionExist = async (ctx, next) => {
    const question = await Question.findById(ctx.params.id).select('+questioner')
    if (!question) {
        ctx.throw(404, '问题不存在')
    }
    ctx.state.question = question
    await next()
}
const cheackCommentExist = async (ctx, next) => {
    const comment = await Comment.findById(ctx.params.id).select('+commentator')
    console.log(comment);
    if (!comment) {
        ctx.throw(404, '评论不存在')
    }
    //删改查评论检查此逻辑
    if (ctx.params.questionId && ctx.params.questionId !== comment.questionId) {
        ctx.throw(404, '此问题不存在该评论')
    }
    if (ctx.params.answerId && ctx.params.answerId !== comment.answerId) {
        ctx.throw(404, '此答案不存在该评论')
    }
    ctx.state.comment = comment
    await next()
}
const cheackAnswerExist = async (ctx, next) => {
    const answer = await Answer.findById(ctx.params.id).select('+answerer')
    console.log(answer);
    if (!answer) {
        ctx.throw(404, '答案不存在')
    }
    //删改查答案检查此逻辑，点赞，踩答案不检查
    if (ctx.params.questionId && ctx.params.questionId !== answer.questionId) {
        ctx.throw(404, '此问题不存在该答案')
    }
    ctx.state.answer = answer
    await next()
}
const cheackQuestionOwner = async (ctx, next) => {
    const {
        question,
        user
    } = ctx.state
    if (question.questioner.toString() !== user._id) {
        ctx.throw(403, '您没有此权限')
    }
    await next()
}
const cheackAnswesOwner = async (ctx, next) => {
    const {
        answer,
        user
    } = ctx.state
    if (answer.answerer.toString() !== user._id) {
        ctx.throw(403, '您没有此权限')
    }
    await next()
}
const cheackCommentOwner = async (ctx, next) => {
    const {
        comment,
        user
    } = ctx.state
    if (comment.commentator.toString() !== user._id) {
        ctx.throw(403, '您没有此权限')
    }
    await next()
}

module.exports = {
    cheackUserExist,
    cheackTopicExist,
    cheackQuestionExist,
    cheackQuestionOwner,
    cheackAnswerExist,
    cheackAnswesOwner,
    cheackCommentExist,
    cheackCommentOwner
}